#include "file_manger.h"
#include "log.h"
#include <stdlib.h>
#include <string.h>



unsigned int hash(const char* str) {
    unsigned int hash = 0;
    while (*str) {
        hash = 31 * hash + (*str++);
    }
    return hash % TABLE_SIZE;
}

HashTable* createHashTable() {
    HashTable* hashTable = (HashTable*)malloc(sizeof(HashTable));
    if (hashTable == NULL) {
        ERR("creat hash table error\n");
        return NULL;
    }
    for (int i = 0; i < TABLE_SIZE; ++i) {
        hashTable->table[i] = NULL;
    }
    hashTable->file_cnt = 0;
    return hashTable;
}

void insertHashTable(HashTable* hashTable, file_lock_t* data) {
    unsigned int index = hash(data->file_name);
    HashNode* newNode = (HashNode*)malloc(sizeof(HashNode));
    if (newNode == NULL) {
        ERR("new node error\n");
        return;
    }
    newNode->data = data;
    //next节点作用是哈希冲突，即一个hash值对应了好几个节点
    newNode->next = hashTable->table[index];
    hashTable->table[index] = newNode;

    hashTable->file_cnt ++;
}

file_lock_t* findInHashTable(HashTable* hashTable, const char* targetStr) {
    unsigned int index = hash(targetStr);
    HashNode* node = hashTable->table[index];
    while (node != NULL) {
        //处理哈希冲突
        if (strcmp(node->data->file_name, targetStr) == 0) {
            return node->data;
        }
        node = node->next;
    }
    return NULL;
}

void free_file_lock(file_lock_t* file_lock) {
    if (file_lock != NULL) {
        // 销毁读写锁
        pthread_rwlock_destroy(&file_lock->rwlock);
        // 释放 file_lock 结构体
        free(file_lock);
    }
}


void delete_hash_node(HashTable* hash_table, const char* file_name) {
    // 计算哈希值
    unsigned int hash_value = hash(file_name);

    // 指向哈希表中的链表头
    HashNode* current = hash_table->table[hash_value];
    HashNode* prev = NULL;

    // 遍历链表
    while (current != NULL) {
        // 检查文件名是否匹配
        if (strcmp(current->data->file_name, file_name) == 0) {
            // 如果是链表头节点
            if (prev == NULL) {
                hash_table->table[hash_value] = current->next;
            } else {
                // 如果不是链表头节点，调整前一个节点的指针
                prev->next = current->next;
            }

            // 释放 file_lock_t 结构体
            free_file_lock(current->data);
            // 释放 HashNode 结构体
            free(current);
            hash_table->file_cnt--;
            return; // 删除成功，退出函数
        }

        // 移动到下一个节点
        prev = current;
        current = current->next;
    }
}

